package com.lzx.adx.report.controller.v1.aqy;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.XhsCovertAqyEventTypeEnums;
import com.lzx.adx.report.model.aqy.AqyRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.biz.product.XhsChannelHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RequestMapping("/aqy/xhs")
@RestController
@Slf4j
public class AqyXhsController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    public static final String apiDesc = "爱奇艺-小红书";


    @GetMapping("/report")
    public ResponseEntity report(AqyRequest aqyRequest, HttpServletRequest request) {

        log.info("接收到【{}】的请求参数为{}", apiDesc, JsonUtils.toJsonString(aqyRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(aqyRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(aqyRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportDTO.setImeiSum(aqyRequest.getImei());
        reportDTO.setImei("");
        reportDTO.setOaidSum(aqyRequest.getOaidSum());
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });

        //获取配置信息
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(aqyRequest.getDspId());
        //3.处理参数和URL
        String resultUrl = XhsChannelHelper.covertXhsReport(reportDTO, accountDTO);
        log.info("账户号为{}，完整的小红书请求地址为{}", aqyRequest.getDspId(), resultUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(resultUrl).execute().body();
        log.info("账户号为{}，上报小红书的接口，响应的结果为{}", aqyRequest.getDspId(), body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        //响应状态码成功
        if (jsonObject.getInteger("code").equals(0)) {
            return ResponseEntity.ok(new Result());
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }


    @GetMapping("/ios/report")
    public ResponseEntity iosReport(AqyRequest aqyRequest, HttpServletRequest request) {
        log.info("接收到爱奇艺-小红书ios的请求参数为{}", JsonUtils.toJsonString(aqyRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(aqyRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(aqyRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        //获取配置信息
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(aqyRequest.getDspId());
        //3.处理参数和URL
        String resultUrl = UrlUtil.handXhsIosReplace(reportDTO, accountDTO);
        log.info("账户号为{}，完整的爱奇艺到小红书ios请求地址为{}", aqyRequest.getDspId(), resultUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(resultUrl).execute().body();
        log.info("账户号为{}，完整的爱奇艺到小红书ios的接口，响应的结果为{}", aqyRequest.getDspId(), body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        //响应状态码成功
        if (jsonObject.getInteger("code").equals(0)) {
            return ResponseEntity.ok(new Result());
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }


    /**
     * 饿了么回传
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String click_id, String conv_type, String conv_ts) throws Exception {
        if (StringUtils.isNotBlank(requestId)) {
            click_id = requestId;
        }
        log.info("接收了小红书回调信息，请求流水号{},回调类型为{}，回调时间{}", click_id, conv_type, conv_ts);
        if (StringUtils.isBlank(conv_type)) {
            log.info("请求参数异常，event_type{},event_time{}", conv_type, conv_ts);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", click_id);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(conv_type);
            reportDTO.setResultTime(conv_ts);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,conv_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        log.info("从数据库查询的数据为{}", JsonUtils.toJsonString(reportDTO));

        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());

        String sspExtend = accountDTO.getSspExtend();
        //如果不为空，且sspExtend
        if (StringUtils.isNotBlank(sspExtend)) {
            JSONObject jsonObject = JSONObject.parseObject(sspExtend);
            Double per = jsonObject.getDouble("per");
            if (Objects.nonNull(per)) {

                if (!AdPerUtil.randomPer(per)) {
                    log.info("流水号为 {} 超出了比例外，本次随机的值为{}，dspId为{}", reportDTO.getBizRequestId(), per, reportDTO.getDspId());
                    return ResponseEntity.ok(new Result());
                }
            }
        }


        String callback = reportDTO.getCallback();
        String decodeUrl = URLUtil.decode(callback, StandardCharsets.UTF_8);
        //3.获取映射的结果
        String eventType = XhsCovertAqyEventTypeEnums.getQqyCode(conv_type);
        if (StringUtils.isBlank(eventType)) {
            log.info("饿了么的回传类型为{}，找不到爱奇艺的映射,不做接口调用回传了，直接返回", eventType);

            return ResponseEntity.ok(new Result());
        }
        //4.拼装最好的完整链接
        String finalResultUrl = decodeUrl + "&event_type=" + eventType;


        log.info("elm给{}上报回传结果，完整的URl{}", apiDesc, finalResultUrl);
        HttpRequest body = HttpUtil.createGet(finalResultUrl);
        String result = body.execute().body();
        log.info("账号为{} 爱奇艺接收了饿了么的回传接口，响应的结果为{}", accountDTO.getId(), result);
        JSONObject jsonObject = JSONObject.parseObject(result);

        //响应状态码成功
        if (jsonObject.getInteger("status").equals(200)) {
            return ResponseEntity.ok(new Result());
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
    }


    /**
     * 饿了么回传
     *
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/ios/callback")
    public ResponseEntity iosCallBackUrl(String requestId, String click_id, String conv_type, String conv_ts) throws Exception {
        log.info("接收了爱奇艺小红书IOS回调信息，请求流水号{},回调类型为{}，回调时间{}", click_id, conv_type, conv_ts);
        if (StringUtils.isBlank(requestId) || StringUtils.isBlank(click_id)) {
            log.info("接收了爱奇艺小红书IOS回调信息,请求流水号空 不作处理");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        if (StringUtils.isNotBlank(requestId)) {
            click_id = requestId;
        }
        if (StringUtils.isBlank(conv_type)) {
            log.info("流水号{}请求参数异常，event_type{},event_time{}", click_id, conv_type, conv_ts);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        if (!"REGISTER".equals(conv_type)) {
            log.info("爱奇艺小红书IOS回调信息的回传类型不是注册不做接口调用回传了，直接返回");
            return ResponseEntity.ok(new Result());
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", click_id);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(conv_type);
            reportDTO.setResultTime(conv_ts);
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,conv_type);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String callback = reportDTO.getCallback();
        String decodeUrl = URLUtil.decode(callback, StandardCharsets.UTF_8);
        //4.拼装最好的完整链接
        String finalResultUrl = decodeUrl + "&event_type=" + 0;
        log.info("账号为{} 流水号{}小红书IOS回传爱奇艺完整的URl{}", accountDTO.getId(), click_id, finalResultUrl);
        HttpRequest body = HttpUtil.createGet(finalResultUrl);
        String result = body.execute().body();
        log.info("账号为{} 流水号{} 小红书IOS回传爱奇艺接口响应的结果为{}", accountDTO.getId(), click_id, result);
        return ResponseEntity.ok(new Result());
    }


}
